package com.mainbo.androidframework.utils;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;


import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.mainbo.androidframework.App;
import com.mainbo.androidframework.R;

/**
 * @author wei
 *         <b>创建时间</b> 2015/9/27
 */
public class ToastUtils {
    private static Toast toast;
    private static Handler mHandler = new Handler();
    private static Runnable r = new Runnable() {
        public void run() {
            toastCancel();
        }
    };

    private synchronized static void toastCancel() {
        if(toast!=null){
            toast.cancel();
            toast = null;
        }
    }

    public static void showToast(String msg) {
        showToast(App.mContext, msg, Gravity.BOTTOM);
    }
    /**
     * 弹出Toast信息
     *
     * @param context
     * @param msg
     */
    public static void showToast(Context context, String msg, int gravity) {
        showToast(context, msg, gravity, Toast.LENGTH_SHORT);
    }

    /**
     * 弹出Toast信息
     *
     * @param context
     * @param msg
     */
    public static void showToast(Context context, String msg, int gravity,
                                 int duration) {
        try {
            if(toast!=null){
                ((TextView)toast.getView().findViewById(R.id.toast_text)).setText(msg);
                toast.setDuration(duration);
            }else{
                toast = new Toast(context);
                View toastView = LayoutInflater.from(context).inflate(
                        R.layout.layout_gray_toast, null);
                TextView msgText = (TextView) toastView.findViewById(R.id.toast_text);
                msgText.setVisibility(View.VISIBLE);
                msgText.setText(msg);
                msgText.setTextColor(ContextCompat.getColor(context,R.color.white));
                msgText.setTextSize(14);
                toast.setView(toastView);
                toast.setDuration(duration);
                toast.setGravity(gravity, 0, 40);
                toast.show();
            }
            mHandler.postDelayed(r, duration);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
